var restify = require('restify');

function getRandomIp() {
  let range = (x, y) => Math.random() * (y - x) + x;
  return `${Math.floor(range(0, 256))}.${Math.floor(range(0, 256))}.${Math.floor(range(0, 256))}.${Math.floor(range(0, 256))}`;
}

function respond(req, res, next) {
  //无准考证查询
  var decoder = require('ling-cet-decoder');
  var request = require('request');
  var iconv = require('iconv-lite');
  var cheerio = require('cheerio');

  var name = req.params.name,
    school = req.params.school ? req.params.school : "浙江师范大学",
    cetType;
    //1 for CET4, 2 for CET6
    if (req.params.level == "4") {
      cetType = 1;
    } else {
      cetType = 2;
    }

  // 准考证找回
  request.post({
    url: 'http://find.cet.99sushe.com/search',
    encoding: null,
    body: decoder.getEncryptReqBody(cetType, school, name)
  }, function (err, req, bodyBuf) {
    if (err) {
      throw new Error(err);
    }
    var ticket = decoder.decryptResBody(bodyBuf);

    // 查询
    request.post({
        url: 'http://www.chsi.com.cn/cet/query?zkzh='+ticket+'&xm='+encodeURIComponent(name.slice(0, 3)),
        gzip: true,
        headers: {
            'Referer': 'http://www.chsi.com.cn/cet/',
            'Accept-Encoding': 'gzip',
            'X-Forwarded-For': getRandomIp()
        }
    }, function (err, req, bodyBuf) {
        if (err) {
            throw new Error(err);
        }
        var $ = cheerio.load(bodyBuf);
        var school = $('.cetTable tr:nth-child(2) td').text();
        var score_data;
        try {
          var _rawStrArr = $('.cetTable tr:last-child').html().split("<br>");
          score_data = _rawStrArr.map(s => {
            return (s.replace('color666', '')
              .replace(/[\t\n\r]*/g, '')
              .replace(/&#([^;]+)/g, '')
              .match(/([0-9]+)/g) || [false])[0];
          });
        } catch (e) {
          res.send({'error': "not found"});
          next();
        }
        var score = {
            'ticket': ticket,
            'name': name,
            'school': school,
            'total': parseFloat(score_data[0]),
            'listening': parseFloat(score_data[1]),
            'reading': parseFloat(score_data[2]),
            'writing': parseFloat(score_data[3]),
        }
        res.send(score);
        console.log(JSON.stringify(score));
        next();
    })
    
  });
}

var server = restify.createServer();
server.get('/cet/:level/:name', respond);
server.get('/cet/:level/:name/:school', respond);

server.listen(8080, function() {
  console.log('%s listening at %s', server.name, server.url);
});
